<!DOCTYPE html>
<html lang="zh-CN">
<!--浏览器搞笑标题-->
<script type="text/javascript" src="/js/FunnyTitle.js"></script>






<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/binblog/img/binblog.ico">
  <link rel="icon" type="image/png" href="/binblog/img/binblog.ico">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="">
  <meta name="author" content="leo-bin">
  <meta name="keywords" content="">
  <title>分布式场景下的全局唯一id生成方案 - 阿斌的个人博客</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/binblog/lib/hint/hint.min.css" />

  
    <link  rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.0.0/styles/dracula.min.css" />
  

  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_yg9cfy8wd6.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_pjno9b9zyxs.css">


<link  rel="stylesheet" href="/binblog/css/main.css" />

<!-- 自定义样式保持在最底部 -->


<meta name="generator" content="Hexo 4.2.1"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/binblog/">&nbsp;<strong>Abin的Blog</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/binblog/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/binblog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/binblog/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/binblog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/binblog/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="view intro-2" id="background" parallax=true
         style="background: url('/binblog/img/6.webp') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="container text-center white-text fadeInUp">
            <span class="h2" id="subtitle">
              
            </span>

            
              
  <div class="mt-3 post-meta">
    <i class="iconfont icon-date-fill" aria-hidden="true"></i>
    <time datetime="2020-05-31 00:41">
      2020年5月31日 凌晨
    </time>
  </div>


<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      1.9k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      23
       分钟
    </span>
  

  
  
    
      <!-- LeanCloud 统计文章PV -->
      <span id="leancloud-post-views-container" class="post-meta" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="leancloud-post-views"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <div class="post-content mx-auto" id="post">
            
              <p class="note note-info">
                
                  本文最后更新于：2020年5月31日 凌晨
                
              </p>
            
            <article class="markdown-body">
              <h1 id="全局唯一id生成方案"><a href="#全局唯一id生成方案" class="headerlink" title="全局唯一id生成方案"></a><strong>全局唯一id生成方案</strong></h1><h2 id="背景"><a href="#背景" class="headerlink" title="背景"></a><strong>背景</strong></h2><p><strong>唯一id是我们在开发系统中不可避免的一个大问题。</strong></p>
<p><strong>诸如登陆业务中需要的sessionId，或者userId，以及消息队列中用到的msgId，还有涉及到金钱利益相关的订单id等等。。。</strong></p>
<p><strong>尤其是分布式系统中，如何生成一个适合具体场景，还要满足各方面的性能的全局唯一id呢?</strong></p>
<p><strong>本文搜寻了网上的一些方案，在这里进行总结。</strong></p>
<h2 id="1-数据库主键自增"><a href="#1-数据库主键自增" class="headerlink" title="1.数据库主键自增"></a><strong>1.数据库主键自增</strong></h2><h3 id="1）介绍"><a href="#1）介绍" class="headerlink" title="1）介绍"></a><strong>1）介绍</strong></h3><p><strong>利用数据库主键自增，我们可以将数据插入数据库时得到它生成的唯一id</strong></p>
<h3 id="2）分析"><a href="#2）分析" class="headerlink" title="2）分析"></a><strong>2）分析</strong></h3><p><strong>但是，这样子一来，如果数据在插入的过程中服务器炸了，那么生成id这一业务就会因此停滞</strong></p>
<p><strong>从而影响到其他的业务！</strong></p>
<h2 id="2-UUID"><a href="#2-UUID" class="headerlink" title="2.UUID"></a><strong>2.UUID</strong></h2><h3 id="1）介绍-1"><a href="#1）介绍-1" class="headerlink" title="1）介绍"></a><strong>1）介绍</strong></h3><p><strong>UUID (Universally Unique Identifier) 全局唯一标识符</strong></p>
<p><strong>UUID每次都会生成一个32位长的id，这个id由连字符组成五个部分</strong></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-number">99</span>bd1571-<span class="hljs-number">7</span>b89-<span class="hljs-number">4e47</span>-<span class="hljs-number">9f</span>18-<span class="hljs-number">0f</span>f52002a6d1</code></pre></div>
<h3 id="2）分析-1"><a href="#2）分析-1" class="headerlink" title="2）分析"></a><strong>2）分析</strong></h3><p><strong>因为jdk内置了专用的UUID的api，所以我们可以很方便的直接使用它</strong></p>
<p><strong>但是，由于通过UUID生成的id很长，足足有32位！而且，它是无序的！</strong></p>
<p><strong>因为无序的原因，可能会导致在插入过程中B+树索引的分裂次数增多</strong></p>
<p><strong>所以导致入库的时候性能很差！所以这里不推荐使用UUID。</strong></p>
<p><strong>数据页的结构：</strong></p>
<p><strong><img src="https://bins-pic.oss-cn-shanghai.aliyuncs.com/mypic/数据页的结构图.jpg" srcset="/binblog/img/loading.gif" alt=""></strong></p>
<p><strong>B+树索引的分裂：</strong></p>
<p><strong>1.一个索引的结构就是一个b+树。</strong></p>
<p><strong>2.一个b+树的节点存储了多个主键值，而一个节点的基本单位就是一个数据页。</strong></p>
<p><strong>3.数据页内的元素之间通过指针相连，形成一个单链表，而数据页之间也是通过链表相连</strong></p>
<p><strong>4.只不过这里需要注意的是，下一个数据页的头结点一定是连接了上一个数据页的尾节点</strong></p>
<p><strong>5.如果插入数据的顺序是有序的，那么就会按照先将元素填满一个数据页</strong></p>
<p><strong>6.当一个数据页填满时，然后再分裂下一个数据页。</strong></p>
<p><strong>7.数据页之间以及数据页内部是有序的，一定要满足下一个数据页的头节点一定要大于上一个数据页的尾节点</strong></p>
<p><strong>8.一旦再插入时不满足这个条件，就会进行内部交换达到有序</strong></p>
<p><strong>9.由此可见，如果插入的主键是杂乱无序的话，这个效率是很低的。</strong></p>
<p><strong>10.这也是为什么数据库有默认的主键递增的概念，就是为了保证插入时的主键是有序的。</strong></p>
<h3 id="3）参考代码"><a href="#3）参考代码" class="headerlink" title="3）参考代码"></a><strong>3）参考代码</strong></h3><div class="hljs"><pre><code class="hljs java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">synchronized</span> String <span class="hljs-title">getNextId</span><span class="hljs-params">()</span> </span>&#123;
    <span class="hljs-keyword">return</span> UUID.randomUUID().toString();
&#125;</code></pre></div>
<h3 id="4）测试代码"><a href="#4）测试代码" class="headerlink" title="4）测试代码"></a><strong>4）测试代码</strong></h3><div class="hljs"><pre><code class="hljs java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10000</span>; i++) &#123;
        <span class="hljs-keyword">new</span> Thread(<span class="hljs-keyword">new</span> Runnable() &#123;
            <span class="hljs-meta">@Override</span>
            <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>&#123;
                System.out.println(getNextId());
            &#125;
        &#125;).start();
    &#125;
&#125;</code></pre></div>
<h3 id="5）测试结果"><a href="#5）测试结果" class="headerlink" title="5）测试结果"></a><strong>5）测试结果</strong></h3><p><strong><img src="https://bins-pic.oss-cn-shanghai.aliyuncs.com/mypic/uuid.jpg" srcset="/binblog/img/loading.gif" alt=""></strong></p>
<h2 id="3-雪花片算法"><a href="#3-雪花片算法" class="headerlink" title="3.雪花片算法"></a><strong>3.雪花片算法</strong></h2><h3 id="1）介绍-2"><a href="#1）介绍-2" class="headerlink" title="1）介绍"></a><strong>1）介绍</strong></h3><p><strong>snowflake是Twitter开源的分布式ID生成算法，结果是一个long型的ID。</strong></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-number">446744090957189120</span></code></pre></div>
<h3 id="2）分析-2"><a href="#2）分析-2" class="headerlink" title="2）分析"></a><strong>2）分析</strong></h3><p><strong>SnowFlake所生成的ID一共可以分成四部分：</strong></p>
<p><strong><img src="https://bins-pic.oss-cn-shanghai.aliyuncs.com/mypic/雪花片算法结构.png" srcset="/binblog/img/loading.gif" alt=""></strong></p>
<p><strong>第一位，占位用</strong></p>
<p><strong>占用1bit，其值始终是0，没有实际作用</strong></p>
<p><strong>第二位，时间戳</strong></p>
<p><strong>占用41bit，精确到毫秒，总共可以容纳约140年的时间！</strong></p>
<p><strong>第三位，工作机器id</strong></p>
<p><strong>占用10bit，其中高位5bit是数据中心ID（datacenterId），低位5bit是工作节点ID（workerId）</strong></p>
<p><strong>最多可以容纳1024个节点！</strong></p>
<p><strong>第四位，序列号</strong></p>
<p><strong>占用12bit，这个值在同一毫秒同一节点上从0开始不断累加，最多可以累加到4095</strong></p>
<p><strong>SnowFlake算法在同一毫秒内最多可生成多少全局唯一ID？只需做一个简单乘法</strong></p>
<p><strong>同一毫秒的ID数量 = 1024 X 4096 = 4194304</strong></p>
<p><strong>大概是400百万个不同的递增id！</strong></p>
<p><strong>这个数字在绝大多数并发场景下都是够用的！</strong></p>
<p><strong>也就是说，通过这个算法生成的id能在非常短的时间内（毫秒级）生成一个全局递增的id！</strong></p>
<p><strong>缺点：如果涉及到分布式环境每台机器上的时钟不可能完全同步，有时候也会出现不是全局递增的情况。</strong></p>
<p><strong>下面给出一种可行的代码</strong></p>
<h3 id="3）参考代码-1"><a href="#3）参考代码-1" class="headerlink" title="3）参考代码"></a><strong>3）参考代码</strong></h3><div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SnowFlake</span> </span>&#123;
    <span class="hljs-comment">/**</span>
<span class="hljs-comment">     * 初始时间截 (2017-01-01)</span>
<span class="hljs-comment">     */</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">long</span> INITIAL_TIME_STAMP = <span class="hljs-number">1483200000000L</span>;
    <span class="hljs-comment">/**</span>
<span class="hljs-comment">     * 机器id所占的位数</span>
<span class="hljs-comment">     */</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">long</span> WORKER_ID_BITS = <span class="hljs-number">5L</span>;
    <span class="hljs-comment">/**</span>
<span class="hljs-comment">     * 数据标识id所占的位数</span>
<span class="hljs-comment">     */</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">long</span> DATACENTER_ID_BITS = <span class="hljs-number">5L</span>;
    <span class="hljs-comment">/**</span>
<span class="hljs-comment">     * 支持的最大机器id，结果是31 (这个移位算法可以很快的计算出几位二进制数所能表示的最大十进制数)</span>
<span class="hljs-comment">     */</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">long</span> MAX_WORKER_ID = ~(-<span class="hljs-number">1L</span> &lt;&lt; WORKER_ID_BITS);
    <span class="hljs-comment">/**</span>
<span class="hljs-comment">     * 支持的最大数据标识id，结果是31</span>
<span class="hljs-comment">     */</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">long</span> MAX_DATACENTER_ID = ~(-<span class="hljs-number">1L</span> &lt;&lt; DATACENTER_ID_BITS);
    <span class="hljs-comment">/**</span>
<span class="hljs-comment">     * 序列在id中占的位数</span>
<span class="hljs-comment">     */</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">long</span> SEQUENCE_BITS = <span class="hljs-number">12L</span>;
    <span class="hljs-comment">/**</span>
<span class="hljs-comment">     * 机器ID的偏移量(12)</span>
<span class="hljs-comment">     */</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">long</span> WORKERID_OFFSET = SEQUENCE_BITS;
    <span class="hljs-comment">/**</span>
<span class="hljs-comment">     * 数据中心ID的偏移量(12+5)</span>
<span class="hljs-comment">     */</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">long</span> DATACENTERID_OFFSET = WORKER_ID_BITS + SEQUENCE_BITS;
    <span class="hljs-comment">/**</span>
<span class="hljs-comment">     * 时间截的偏移量(5+5+12)</span>
<span class="hljs-comment">     */</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">long</span> TIMESTAMP_OFFSET = SEQUENCE_BITS + WORKER_ID_BITS + DATACENTER_ID_BITS;
    <span class="hljs-comment">/**</span>
<span class="hljs-comment">     * 生成序列的掩码，这里为4095 (0b111111111111=0xfff=4095)</span>
<span class="hljs-comment">     */</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">long</span> SEQUENCE_MASK = ~(-<span class="hljs-number">1L</span> &lt;&lt; SEQUENCE_BITS);
    <span class="hljs-comment">/**</span>
<span class="hljs-comment">     * 工作节点ID(0~31)</span>
<span class="hljs-comment">     */</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">long</span> workerId;
    <span class="hljs-comment">/**</span>
<span class="hljs-comment">     * 数据中心ID(0~31)</span>
<span class="hljs-comment">     */</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">long</span> dataCenterId;
    <span class="hljs-comment">/**</span>
<span class="hljs-comment">     * 毫秒内序列(0~4095)</span>
<span class="hljs-comment">     */</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">long</span> sequence = <span class="hljs-number">0L</span>;
    <span class="hljs-comment">/**</span>
<span class="hljs-comment">     * 上次生成ID的时间截</span>
<span class="hljs-comment">     */</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">long</span> lastTimestamp = -<span class="hljs-number">1L</span>;


    <span class="hljs-comment">/**</span>
<span class="hljs-comment">     * <span class="hljs-doctag">@param</span> workerId     工作ID (0~31)</span>
<span class="hljs-comment">     * <span class="hljs-doctag">@param</span> dataCenterId 数据中心ID (0~31)</span>
<span class="hljs-comment">     */</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">SnowFlake</span><span class="hljs-params">(<span class="hljs-keyword">long</span> workerId, <span class="hljs-keyword">long</span> dataCenterId)</span> </span>&#123;
        <span class="hljs-keyword">if</span> (workerId &gt; MAX_WORKER_ID || workerId &lt; <span class="hljs-number">0</span>) &#123;
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> IllegalArgumentException(String.format(<span class="hljs-string">"WorkerID 不能大于 %d 或小于 0"</span>, MAX_WORKER_ID));
        &#125;
        <span class="hljs-keyword">if</span> (dataCenterId &gt; MAX_DATACENTER_ID || dataCenterId &lt; <span class="hljs-number">0</span>) &#123;
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> IllegalArgumentException(String.format(<span class="hljs-string">"DataCenterID 不能大于 %d 或小于 0"</span>, MAX_DATACENTER_ID));
        &#125;
        <span class="hljs-keyword">this</span>.workerId = workerId;
        <span class="hljs-keyword">this</span>.dataCenterId = dataCenterId;
    &#125;
    
    <span class="hljs-comment">/**</span>
<span class="hljs-comment">     * 获得下一个ID (用同步锁保证线程安全)</span>
<span class="hljs-comment">     *</span>
<span class="hljs-comment">     * <span class="hljs-doctag">@return</span> SnowflakeId</span>
<span class="hljs-comment">     */</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">synchronized</span> <span class="hljs-keyword">long</span> <span class="hljs-title">nextId</span><span class="hljs-params">()</span> </span>&#123;
        <span class="hljs-keyword">long</span> timestamp = System.currentTimeMillis();
        <span class="hljs-comment">// 如果当前时间小于上一次ID生成的时间戳，说明系统时钟回退过这个时候应当抛出异常</span>
        <span class="hljs-keyword">if</span> (timestamp &lt; lastTimestamp) &#123;
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> RuntimeException(<span class="hljs-string">"当前时间小于上一次记录的时间戳！"</span>);
        &#125;
        <span class="hljs-comment">// 如果是同一时间生成的，则进行毫秒内序列</span>
        <span class="hljs-keyword">if</span> (lastTimestamp == timestamp) &#123;
            sequence = (sequence + <span class="hljs-number">1</span>) &amp; SEQUENCE_MASK;
            <span class="hljs-comment">// sequence等于0说明毫秒内序列已经增长到最大值</span>
            <span class="hljs-keyword">if</span> (sequence == <span class="hljs-number">0</span>) &#123;
                <span class="hljs-comment">// 阻塞到下一个毫秒,获得新的时间戳</span>
                timestamp = tilNextMillis(lastTimestamp);
            &#125;
        &#125;
        <span class="hljs-comment">// 时间戳改变，毫秒内序列重置</span>
        <span class="hljs-keyword">else</span> &#123;
            sequence = <span class="hljs-number">0L</span>;
        &#125;
        <span class="hljs-comment">// 上次生成ID的时间截</span>
        lastTimestamp = timestamp;
        <span class="hljs-comment">// 移位并通过或运算拼到一起组成64位的ID</span>
        <span class="hljs-keyword">return</span> ((timestamp - INITIAL_TIME_STAMP) &lt;&lt; TIMESTAMP_OFFSET) | (dataCenterId &lt;&lt; DATACENTERID_OFFSET)
                | (workerId &lt;&lt; WORKERID_OFFSET) | sequence;
    &#125;
    
    <span class="hljs-comment">/**</span>
<span class="hljs-comment">     * 阻塞到下一个毫秒，直到获得新的时间戳</span>
<span class="hljs-comment">     *</span>
<span class="hljs-comment">     * <span class="hljs-doctag">@param</span> lastTimestamp 上次生成ID的时间截</span>
<span class="hljs-comment">     * <span class="hljs-doctag">@return</span> 当前时间戳</span>
<span class="hljs-comment">     */</span>
    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">long</span> <span class="hljs-title">tilNextMillis</span><span class="hljs-params">(<span class="hljs-keyword">long</span> lastTimestamp)</span> </span>&#123;
        <span class="hljs-keyword">long</span> timestamp = System.currentTimeMillis();
        <span class="hljs-keyword">while</span> (timestamp &lt;= lastTimestamp) &#123;
            timestamp = System.currentTimeMillis();
        &#125;
        <span class="hljs-keyword">return</span> timestamp;
    &#125;</code></pre></div>
<h3 id="4）测试代码-1"><a href="#4）测试代码-1" class="headerlink" title="4）测试代码"></a><strong>4）测试代码</strong></h3><p><strong>这里启动了10000个线程同时去调用nextId方法</strong></p>
<div class="hljs"><pre><code class="hljs java">    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;
        <span class="hljs-keyword">final</span> SnowFlake idGenerator = <span class="hljs-keyword">new</span> SnowFlake(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>);
        <span class="hljs-comment">// 线程池并行执行10000次ID生成</span>
        ExecutorService executorService = Executors.newCachedThreadPool();
        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10000</span>; i++) &#123;
            executorService.execute(<span class="hljs-keyword">new</span> Runnable() &#123;
                <span class="hljs-meta">@Override</span>
                <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>&#123;
                    <span class="hljs-keyword">long</span> id = idGenerator.nextId();
                    System.out.println(id);
                &#125;
            &#125;);
        &#125;
        executorService.shutdown();
    &#125;
&#125;</code></pre></div>
<h3 id="5）测试结果-1"><a href="#5）测试结果-1" class="headerlink" title="5）测试结果"></a><strong>5）测试结果</strong></h3><p><strong><img src="https://s1.ax1x.com/2020/05/02/JxuPYt.jpg" srcset="/binblog/img/loading.gif" alt="JxuPYt.jpg"></strong></p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a><strong>总结</strong></h2><p><strong>1.本次介绍了id生成的几种可行的方案。</strong></p>
<p><strong>2.其实id生成方案远不止这些，一定是根据具体场景来选择合适的技术。</strong></p>
<p><strong>3.学无止境，加油！</strong></p>
<h2 id="参考"><a href="#参考" class="headerlink" title="参考"></a><strong>参考</strong></h2><p><strong>1.<a href="https://www.cnblogs.com/haoxinyue/p/5208136.html" target="_blank" rel="noopener">https://www.cnblogs.com/haoxinyue/p/5208136.html</a></strong></p>
<p><strong>2.<a href="https://blog.csdn.net/bjweimengshu/article/details/80162731" target="_blank" rel="noopener">https://blog.csdn.net/bjweimengshu/article/details/80162731</a></strong></p>
<p><strong>3.<a href="https://www.qugcloud.cn/2019/05/20/java-snowflake/" target="_blank" rel="noopener">https://www.qugcloud.cn/2019/05/20/java-snowflake/</a></strong></p>

            </article>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/binblog/categories/%E7%AE%97%E6%B3%95/">算法</a>
                    
                  </div>
                
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" target="_blank" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！</p>
              
              
                <div class="post-prevnext row">
                  <div class="post-prev col-6">
                    
                    
                      <a href="/binblog/2020/05/31/%E7%BA%AF%E6%89%8B%E5%86%99LRU%E7%AE%97%E6%B3%95%EF%BC%81/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">纯手写LRU算法！</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </div>
                  <div class="post-next col-6">
                    
                    
                      <a href="/binblog/2020/05/31/%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8Java%E8%AE%BE%E8%AE%A1%E4%B8%80%E4%B8%AA%E7%94%9F%E4%BA%A7%E8%80%85%E6%B6%88%E8%B4%B9%E8%80%85/">
                        <span class="hidden-mobile">如何用Java设计一个简单的生产者消费者</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </div>
                </div>
              
            </div>

            
              <!-- Comments -->
              <div class="comments" id="comments">
                
                
  <div id="vcomments"></div>
  <script defer src="https://cdn.staticfile.org/valine/1.4.14/Valine.min.js" ></script>

  <script type="text/javascript">
    var oldLoadVa = window.onload;
    window.onload = function () {
      oldLoadVa && oldLoadVa();

      new Valine({
        el: "#vcomments",
        app_id: "vsanVmkaurLHyq2Xey9odo5V-gzGzoHsz",
        app_key: "v2hMMe4Mzz3mqpy9jwd7qx8B",
        placeholder: "说点什么吧！",
        path: window.location.pathname,
        avatar: "retro",
        meta: ["nick","mail","link"],
        pageSize: "10",
        lang: "zh-CN",
        highlight: true,
        recordIP: false,
        serverURLs: "",
      });
    };
  </script>
  <noscript>Please enable JavaScript to view the <a href="https://valine.js.org" target="_blank" rel="nofollow noopener noopener">comments
      powered by Valine.</a></noscript>


              </div>
            
          </div>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div id="tocbot"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    
  </main>

  
    <a id="scroll-top-button" href="#" role="button">
      <i class="iconfont icon-arrowup" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  

  

  <footer class="mt-5">
  <div class="text-center py-3">
    <div>
      <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a>
      <i class="iconfont icon-love"></i>
      <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener">
        <span>Fluid</span></a>
    </div>
    
  <div class="statistics">
    
    

    
      
        <!-- LeanCloud 统计PV -->
        <span id="leancloud-site-pv-container" style="display: none">
            总访问量 
            <span id="leancloud-site-pv"></span>
             次
          </span>
      
      
        <!-- LeanCloud 统计UV -->
        <span id="leancloud-site-uv-container" style="display: none">
            总访客数 
            <span id="leancloud-site-uv"></span>
             人
          </span>
      

    
  </div>


    
  <!-- 备案信息 -->
  <div class="beian">
    <a href="http://beian.miit.gov.cn/" target="_blank"
       rel="nofollow noopener">京ICP证123456号</a>
    
      <a
        href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=12345678"
        rel="nofollow noopener"
        class="beian-police"
        target="_blank"
      >
        <span class="beian-police-sep">&nbsp;|&nbsp;</span>
        
          <img src="/binblog/img/police_beian.png" srcset="/binblog/img/loading.gif" alt="police-icon" />
        
        <span>京公网安备12345678号</span>
      </a>
     
  </div>


    
  </div>
</footer>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="/binblog/js/debouncer.js" ></script>
<script  src="/binblog/js/main.js" ></script>

<!-- Plugins -->


  
    <script  src="/binblog/js/lazyload.js" ></script>
  



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
  <script  src="/binblog/js/clipboard-use.js" ></script>



  <script defer>
  (function () {
    // 查询存储的记录
    function getRecord(Counter, target) {
      return new Promise(function (resolve, reject) {
        Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({target})))
          .then(resp => resp.json())
          .then(({results, code, error}) => {
            if (code === 401) {
              throw error;
            }
            if (results && results.length > 0) {
              var record = results[0];
              resolve(record);
            } else {
              Counter('post', '/classes/Counter', {target, time: 0})
                .then(resp => resp.json())
                .then((record, error) => {
                  if (error) {
                    throw error;
                  }
                  resolve(record);
                }).catch(error => {
                console.error('Failed to create', error);
                reject(error);
              });
            }
          }).catch((error) => {
          console.error('LeanCloud Counter Error:', error);
          reject(error);
        });
      })
    }

    // 发起自增请求
    function increment(Counter, incrArr) {
      return new Promise(function (resolve, reject) {
        Counter('post', '/batch', {
          "requests": incrArr
        }).then((res) => {
          res = res.json();
          if (res.error) {
            throw res.error;
          }
          resolve(res);
        }).catch((error) => {
          console.error('Failed to save visitor count', error);
          reject(error);
        });
      });
    }

    // 构建自增请求体
    function buildIncrement(objectId) {
      return {
        "method": "PUT",
        "path": `/1.1/classes/Counter/${ objectId }`,
        "body": {
          "time": {
            '__op': 'Increment',
            'amount': 1
          }
        }
      }
    }

    // 校验是否为有效的 UV
    function validUV() {
      var key = 'LeanCloud_UV_Flag';
      var flag = localStorage.getItem(key);
      if (flag) {
        // 距离标记小于 24 小时则不计为 UV
        if (new Date().getTime() - parseInt(flag) <= 86400000) {
          return false;
        }
      }
      localStorage.setItem(key, new Date().getTime().toString());
      return true;
    }

    function addCount(Counter) {
      var enableIncr = 'true' === 'true' && window.location.hostname !== 'localhost';
      var getterArr = [];
      var incrArr = [];

      // 请求 PV 并自增
      var pvCtn = document.querySelector('#leancloud-site-pv-container');
      if (pvCtn || enableIncr) {
        var pvGetter = getRecord(Counter, 'site-pv').then((record) => {
          incrArr.push(buildIncrement(record.objectId))
          var ele = document.querySelector('#leancloud-site-pv');
          if (ele) {
            ele.innerText = record.time + 1;
            if (pvCtn) {
              pvCtn.style.display = 'inline';
            }
          }
        });
        getterArr.push(pvGetter);
      }

      // 请求 UV 并自增
      var uvCtn = document.querySelector('#leancloud-site-uv-container');
      if (uvCtn || enableIncr) {
        var uvGetter = getRecord(Counter, 'site-uv').then((record) => {
          var vuv = validUV();
          vuv && incrArr.push(buildIncrement(record.objectId))
          var ele = document.querySelector('#leancloud-site-uv');
          if (ele) {
            ele.innerText = record.time + (vuv ? 1 : 0);
            if (uvCtn) {
              uvCtn.style.display = 'inline';
            }
          }
        });
        getterArr.push(uvGetter);
      }

      // 如果是文章，请求文章的浏览数，并自增
      if ('true' === 'true') {
        var viewCtn = document.querySelector('#leancloud-post-views-container');
        if (viewCtn || enableIncr) {
          var target = decodeURI('/binblog/2020/05/31/%E5%88%86%E5%B8%83%E5%BC%8F%E5%9C%BA%E6%99%AF%E4%B8%8B%E7%9A%84%E5%85%A8%E5%B1%80%E5%94%AF%E4%B8%80id%E7%94%9F%E6%88%90%E6%96%B9%E6%A1%88/');
          var viewGetter = getRecord(Counter, target).then((record) => {
            incrArr.push(buildIncrement(record.objectId))
            if (viewCtn) {
              var ele = document.querySelector('#leancloud-post-views');
              if (ele) {
                ele.innerText = (record.time || 0) + 1;
                viewCtn.style.display = 'inline';
              }
            }
          });
          getterArr.push(viewGetter);
        }
      }

      // 如果启动计数自增，批量发起自增请求
      if (enableIncr) {
        Promise.all(getterArr).then(() => {
          incrArr.length > 0 && increment(Counter, incrArr);
        })
      }
    }

    var app_id = 'vsanVmkaurLHyq2Xey9odo5V-gzGzoHsz'
    var app_key = 'v2hMMe4Mzz3mqpy9jwd7qx8B'
    var server_url = ''

    function fetchData(api_server) {
      var Counter = (method, url, data) => {
        return fetch(`${ api_server }/1.1${ url }`, {
          method,
          headers: {
            'X-LC-Id': app_id,
            'X-LC-Key': app_key,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(data)
        });
      };

      addCount(Counter);
    }

    var api_server = app_id.slice(-9) !== '-MdYXbMMI' ? server_url : `https://${ app_id.slice(0, 8).toLowerCase() }.api.lncldglobal.com`;

    if (api_server) {
      fetchData(api_server);
    } else {
      fetch('https://app-router.leancloud.cn/2/route?appId=' + app_id)
        .then(resp => resp.json())
        .then(({api_server}) => {
          fetchData('https://' + api_server);
        });
    }
  })();
</script>






  <script  src="https://cdn.staticfile.org/tocbot/4.11.1/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var boardCtn = $('#board-ctn');
      var boardTop = boardCtn.offset().top;

      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: 'article.markdown-body',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        collapseDepth: 0,
        scrollSmooth: true,
        headingsOffset: -boardTop
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc').css('visibility', 'visible');
      }
    });
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "分布式场景下的全局唯一id生成方案&nbsp;",
      ],
      cursorChar: "_",
      typeSpeed: 70,
      loop: false,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script  src="/binblog/js/local-search.js" ></script>
  <script>
    var path = "/binblog/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      searchFunc(path, 'local-search-input', 'local-search-result');
      this.onclick = null
    }
  </script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />

  <script>
    $('#post img:not(.no-zoom img, img[no-zoom]), img[zoom]').each(
      function () {
        var element = document.createElement('a');
        $(element).attr('data-fancybox', 'images');
        $(element).attr('href', $(this).attr('src'));
        $(this).wrap(element);
      }
    );
  </script>





  

  
    <!-- MathJax -->
    <script>
      MathJax = {
        tex: {
          inlineMath: [['$', '$'], ['\\(', '\\)']]
        },
        options: {
          renderActions: {
            findScript: [10, doc => {
              document.querySelectorAll('script[type^="math/tex"]').forEach(node => {
                const display = !!node.type.match(/; *mode=display/);
                const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display);
                const text = document.createTextNode('');
                node.parentNode.replaceChild(text, node);
                math.start = { node: text, delim: '', n: 0 };
                math.end = { node: text, delim: '', n: 0 };
                doc.math.push(math);
              });
            }, '', false],
            insertedScript: [200, () => {
              document.querySelectorAll('mjx-container').forEach(node => {
                let target = node.parentNode;
                if (target.nodeName.toLowerCase() === 'li') {
                  target.parentNode.classList.add('has-jax');
                }
              });
            }, '', false]
          }
        }
      };
    </script>

    <script async src="https://cdn.staticfile.org/mathjax/3.0.5/es5/tex-svg.js" ></script>

  













  

  

  

  

  

  





<script src="/binblog/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"model":{"jsonPath":"/binblog/live2dw/assets/koharu.model.json"},"display":{"position":"right","width":150,"height":300},"mobile":{"show":true},"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body>
</html>
